//
//  YXTabBar.m
//  彩票
//
//  Created by mac on 15-3-25.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "YXTabBar.h"
#import "YXTabBarButton.h"

@interface YXTabBar ()
// 记录当前选中的按钮
@property (nonatomic, weak) UIButton *currentBtn;

@end

@implementation YXTabBar

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //[self setupAllButtons];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        //[self setupAllButtons];
    }
    return self;
}

- (void)addTabBarButton:(UITabBarItem *)item
{

        YXTabBarButton *btn = [YXTabBarButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:item.image  forState:UIControlStateNormal];
        [btn setBackgroundImage:item.selectedImage forState:UIControlStateSelected
         ];
        //[self addSubview:btn];
        // 添单击
        [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchDown];
        // 给btn一个tag标记
        btn.tag = self.subviews.count;
        if (btn.tag == 0) {
            [self clickBtn:btn];
        }
        [self addSubview:btn];
    

}

/*
 - (void)setupAllButtons
{
    for (int i = 1; i <= 5; i ++) {
        YXTabBarButton *btn = [YXTabBarButton buttonWithType:UIButtonTypeCustom];
        NSString *norImage = [NSString stringWithFormat:@"TabBar%d",i];
        NSString *seletedImage = [NSString stringWithFormat:@"TabBar%dSel",i];
        [btn setBackgroundImage:[UIImage imageNamed:norImage ] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:seletedImage] forState:UIControlStateSelected
         ];
        //[self addSubview:btn];
        // 添单击
        [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchDown];
        // 给btn一个tag标记
         btn.tag = self.subviews.count;
        if (btn.tag == 0) {
            [self clickBtn:btn];
        }
        [self addSubview:btn];
    }
    
}
 */
- (void)clickBtn:(YXTabBarButton *)btn
{
    if ([self.delegate respondsToSelector:@selector(tabBar:from:to:)]) {
        [self.delegate tabBar:self from:self.currentBtn.tag to:btn.tag];
    }
    self.currentBtn.selected = NO;
    btn.selected = YES;
    self.currentBtn = btn;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    int count = self.subviews.count;
    for (int i =0; i < count; i++) {
        YXTabBarButton *btn = self.subviews[i];
        CGFloat W = self.frame.size.width/count;
        CGFloat H = self.frame.size.height;
        CGFloat X = i * W;
        CGFloat Y = 0;
        btn.frame = CGRectMake(X, Y, W, H);
    }
}

@end
